home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 June: Reference Library / Dev.CD Jun 94.toast / Periodicals / develop / develop Issue 11 / develop 11 code / Async Sound Helper / SoundHelper / SoundHelper.c < prev    next >
Encoding:
Text File  |  1992-07-15  |  60.2 KB  |  1,685 lines  |  [TEXT/MPS ]

  1. //=======================================================================================
  2. //
  3. // SoundHelper.c - the Asynchronous Sound Helper
  4. //
  5. // Written by Bryan K. Ressler (Beaker), 2/4/92
  6. //
  7. // Version 1.00, 2/4/92        Original version
  8. //         1.01, 2/20/92    Added SHGetState to fix handle semaphore problem
  9. //         1.02, 3/21/92    Make handle/error checks more explicit, modify
  10. //                             SHPlayStopByRec (to handle channels with no synthesizer)
  11. //         1.03, 4/4/92        Modifications per KO, RC, JR.  Public routines now pascal.
  12. //         1.04, 4/20/92    Reverted to SHPlayPause/SHPlayContinue structure.
  13. //
  14. // The author wishes to acknowledge Jim Reekes, Kip Olsen, Neil Day, and Rich Collyer
  15. // for their vital technical help in the preparation of this code for publication.
  16. //
  17. //=======================================================================================
  18.  
  19. //=======================================================================================
  20. // Includes
  21. //=======================================================================================
  22. #include "Std.h"
  23. #include "SoundHelper.h"
  24. #include "SHPrivate.h"
  25.  
  26. //=======================================================================================
  27. // Statics
  28. //=======================================================================================
  29. static Boolean        gsSHInited = false;            // Flags whether Helper has been inited
  30. static Boolean        *gsSHNeedsTime;                // Pointer to app "SH needs time" flag
  31.  
  32. static SHOutputVars    gsSHOutVars;                // Sound output variables
  33. static SHInputVars    gsSHInVars;                    // Sound input variables
  34.  
  35. //=======================================================================================
  36. // Static prototypes
  37. //=======================================================================================
  38. static long SHNewRefNum(void);
  39. static OSErr SHNewOutRec(SHOutPtr *outRec);
  40. static pascal void SHPlayCompletion(SndChannelPtr channel, SndCommand *command);
  41. static pascal void SHRecordCompletion(SPBPtr inParams);
  42. static OSErr SHInitOutRec(SHOutPtr outRec, long refNum, Handle sound, char handleState);
  43. static void SHReleaseOutRec(SHOutPtr outRec);
  44. static OSErr SHQueueCallback(SndChannel *channel);
  45. static OSErr SHBeginPlayback(SHOutPtr outRec);
  46. static char SHGetState(Handle snd);
  47. static SHOutPtr SHOutRecFromRefNum(long refNum);
  48. static void SHPlayStopByRec(SHOutPtr outRec);
  49. static OSErr SHGetDeviceSettings(long inRefNum, short *numChannels, Fixed *sampleRate,
  50.     short *sampleSize, OSType *compType);
  51.  
  52. //=======================================================================================
  53. //
  54. //    pascal OSErr SHInitSoundHelper(Boolean *attnFlag, short numChannels)
  55. //
  56. //    Summary:
  57. //        This routine initializes the Asynchronous Sound Helper.
  58. //
  59. //    Scope:
  60. //        Public.
  61. //
  62. //    Parameters:
  63. //        attnFlag        Pointer to a application Boolean.  This Boolean will be set to
  64. //                        true when the Helper needs a call to SHIdle.  For example, the
  65. //                        application will have a global Boolean with a name like
  66. //                        "gCallHelper," and will pass the address of that global to
  67. //                        SHInitSoundHelper.  Then, in the application's main event loop,
  68. //                        will simply check gCallHelper, and call SHIdle if it is set.
  69. //        numChannels        Tells the Helper how many output records to allocate. The number
  70. //                        of simultaneous sounds that can be produced by the Helper is
  71. //                        limited by a) the number of simultaneous channels the Sound
  72. //                        Manager allows, and b) the number of output records specified by
  73. //                        this parameter. If you specify zero, a reasonable default (4) is
  74. //                        used.
  75. //
  76. //    Returns:
  77. //        MemError()        If there is one.
  78. //        memFullErr        If the output array was nil but MemError returned noErr.
  79. //        noErr            Otherwise.
  80. //
  81. //    Operation:
  82. //        This routine simply allocates the output records, initializes some statics, and
  83. //        sets a flag that tells whether the Helper has been initialized.
  84. //
  85. //=======================================================================================
  86. pascal OSErr SHInitSoundHelper(Boolean *attnFlag, short numChannels)
  87. {
  88.     OSErr    err;
  89.     
  90.     // Use default number of channels if zero was specified
  91.     if (numChannels == 0)
  92.         numChannels = kSHDefChannels;
  93.     
  94.     // Remember the address of the application's "attention" flag
  95.     gsSHNeedsTime = attnFlag;
  96.     
  97.     // Allocate the channels
  98.     gsSHOutVars.numOutRecs = numChannels;
  99.     gsSHOutVars.outArray = (SHOutPtr)NewPtrClear(numChannels * sizeof(SHOutRec));
  100.  
  101.     // If successful, flag that we're initialized and exit
  102.     if (gsSHOutVars.outArray != nil) {
  103.         gsSHInited = true;
  104.         return(noErr);
  105.     } else {
  106.         // Return some kind of error (MemError if there is one, otherwise make one up)
  107.         err = MemError();
  108.         if (err == noErr)
  109.             err = memFullErr;
  110.         return(err);
  111.     }
  112. }
  113.  
  114. //=======================================================================================
  115. //
  116. //    pascal void SHIdle(void)
  117. //
  118. //    Summary:
  119. //        This routine performs various cleanup operations when sounds have finished
  120. //        playing or recording.
  121. //
  122. //    Scope:
  123. //        Public.
  124. //
  125. //    Parameters:
  126. //        None.
  127. //
  128. //    Returns:
  129. //        Nothing.
  130. //
  131. //    Operation:
  132. //        First, SHIdle clears the flag that indicates an SHIdle call is needed.  Next,
  133. //        SHIdle performs playback cleanup.  It iterates through the output records
  134. //        looking for records that are both in use and complete.  Such records are disposed
  135. //        with SHReleaseOutRec.  This frees the record for use later, and closes the sound
  136. //        channel with the Sound Manager.  Next, SHIdle performs recording cleanup.  It
  137. //        checks if recording is underway and is flagged as complete.  If so, it unlocks
  138. //        the (previously locked) input handle, and checks for errors.  If errors occurred,
  139. //        the input handle is disposed and the recordErr field of the input variable record
  140. //        is filled with the error.  This allows the error to later be reported to the
  141. //        caller when he calls SHGetRecordedSound.  If no error occured, then the sound
  142. //        header is re-written into the input sound handle, this time with the correct
  143. //        length, and the handle is sized down to match the actual number of samples that
  144. //        were recorded.  Then the sound input device is closed and the application is
  145. //        notified that recording is complete through his Boolean completion flag.
  146. //
  147. //=======================================================================================
  148. pascal void SHIdle(void)
  149. {
  150.     short    i;
  151.     OSErr    err;
  152.     long    realSize;
  153.     
  154.     // Immediately turn off the application's "Helper needs time" flag
  155.     *gsSHNeedsTime = false;
  156.  
  157.     // Do playback cleanup
  158.     for (i = 0; i < gsSHOutVars.numOutRecs; i++)
  159.         if (gsSHOutVars.outArray[i].inUse &&
  160.                 gsSHOutVars.outArray[i].channel.userInfo == kSHComplete)
  161.             // We've found a channel that needs closing...
  162.             SHReleaseOutRec(&gsSHOutVars.outArray[i]);
  163.     
  164.     // Do recording cleaunp
  165.     if (gsSHInVars.recording && gsSHInVars.recordComplete) {
  166.         HUnlock(gsSHInVars.inHandle);
  167.         
  168.         if (gsSHInVars.inPB.error && gsSHInVars.inPB.error != abortErr) {
  169.             // An error (other than a manual stop) occurred during recording.  Kill the
  170.             // handle and save the error code.
  171.             gsSHInVars.recordErr = gsSHInVars.inPB.error;
  172.             DisposeHandle(gsSHInVars.inHandle);
  173.             gsSHInVars.inHandle = nil;
  174.         } else {
  175.             // Recording completed normally (which includes abortErr, the "error" that
  176.             // occurs when recording is manually stopped).  We re-write the header (to
  177.             // slam the correct size in there), and size the handle to fit the actual
  178.             // recorded size (which either shortens the handle, or doesn't change its
  179.             // size -- that's why we don't bother checking the error).
  180.             gsSHInVars.recordErr = noErr;
  181.             realSize = gsSHInVars.inPB.count + gsSHInVars.headerLength;
  182.             err = SetupSndHeader(gsSHInVars.inHandle, gsSHInVars.numChannels,
  183.                 gsSHInVars.sampleRate, gsSHInVars.sampleSize, gsSHInVars.compType,
  184.                 kSHBaseNote, realSize, &gsSHInVars.headerLength);
  185.             SetHandleSize(gsSHInVars.inHandle, realSize);        // Shorten the handle
  186.         }
  187.         
  188.         // Error or not, close the recording device, and notify the application that
  189.         // recording is complete, through the recording-completed flag that the caller
  190.         // originally passed into SHRecordStart.
  191.         SPBCloseDevice(gsSHInVars.inRefNum);
  192.         gsSHInVars.recording = false;
  193.         gsSHInVars.inRefNum = 0;
  194.         if (gsSHInVars.appComplete != nil)
  195.             *gsSHInVars.appComplete = true;
  196.     }
  197. }
  198.  
  199. //=======================================================================================
  200. //
  201. //    pascal void SHKillSoundHelper(void)
  202. //
  203. //    Summary:
  204. //        This routine terminates the Asynchronous Sound Helper.
  205. //
  206. //    Scope:
  207. //        Public.
  208. //
  209. //    Parameters:
  210. //        None.
  211. //
  212. //    Returns:
  213. //        Nothing.
  214. //
  215. //    Operation:
  216. //        This routine, after checking that the Helper was previously initialized, stops
  217. //        all current playback and recording, waits 1/60th of a second (to allow the Sound
  218. //        Manager to call our callback routines, SHPlayCompletion and SHRecordCompletion),
  219. //        then calls SHIdle to force cleanup (releasing sound channels and closing the
  220. //        sound input device if appropriate).  Then, SHKillSoundHelper disposes of the
  221. //        output records.
  222. //
  223. //=======================================================================================
  224. pascal void SHKillSoundHelper(void)
  225. {
  226.     short    i;
  227.     long    timeout;
  228.     Boolean    outputClean, inputClean;
  229.     
  230.     if (!gsSHInited)
  231.         return;
  232.  
  233.     SHPlayStopAll();    // Kill all playback
  234.     SHRecordStop();        // Kill recording
  235.     
  236.     // Now sync-wait for everything to clean itself up
  237.     timeout = TickCount() + kSHSyncWaitTimeout;
  238.     do {
  239.         if (*gsSHNeedsTime)
  240.             SHIdle();            // Clean up when required
  241.  
  242.         // Check if all our output channels are cleaned up
  243.         outputClean = true;
  244.         for (i = 0; i < gsSHOutVars.numOutRecs && outputClean; i++)
  245.             if (gsSHOutVars.outArray[i].inUse)
  246.                 outputClean = false;
  247.         
  248.         // Check whether our recording is cleaned up
  249.         inputClean = !gsSHInVars.recording;
  250.         
  251.         if (inputClean && outputClean)
  252.             break;
  253.     } while (TickCount() < timeout);
  254.     
  255.     // Lose our preallocated sound channels
  256.     DisposePtr((Ptr)gsSHOutVars.outArray);
  257. }
  258.  
  259. //=======================================================================================
  260. //
  261. //    long SHNewRefNum(void)
  262. //
  263. //    Summary:
  264. //        This routine returns the next available output reference number.
  265. //
  266. //    Scope:
  267. //        Private.
  268. //
  269. //    Parameters:
  270. //        None.
  271. //
  272. //    Returns:
  273. //        The next available output reference number.
  274. //
  275. //    Operation:
  276. //        The output variable nextRef contains the next available reference number.  This
  277. //        function returns the value of nextRef then increments it.  This way, output ref-
  278. //        erence numbers are unique throughout a session (modulo 2,147,483,647).
  279. //
  280. //=======================================================================================
  281. long SHNewRefNum(void)
  282. {
  283.     return(gsSHOutVars.nextRef++);
  284. }
  285.  
  286. //=======================================================================================
  287. //
  288. //    OSErr SHNewOutRec(SHOutPtr *outRec)
  289. //
  290. //    Summary:
  291. //        This routine attempts to return the first available output record.
  292. //
  293. //    Scope:
  294. //        Private.
  295. //
  296. //    Parameters:
  297. //        outRec        A pointer to an SHOutRecPtr.  This is where SHNewOutRec puts
  298. //                    the pointer to the output record.
  299. //
  300. //    Returns:
  301. //        kSHErrOutaChannels        If no free output record was found.
  302. //        noErr                    Otherwise.
  303. //
  304. //    Operation:
  305. //        SHNewOutRec simply iterates through the output record array looking for a record
  306. //        that is not in use.  If all the records are in use, SHNewOutRec returns the
  307. //        Helper error code kSHErrOutaChannels.  If a record is found, then the address of
  308. //        the record is stored via the VAR parameter, and noErr is returned.
  309. //
  310. //=======================================================================================
  311. OSErr SHNewOutRec(SHOutPtr *outRec)
  312. {
  313.     short    i;
  314.     
  315.     // First look for a free channel among our preallocated output records
  316.     for (i = 0; i < gsSHOutVars.numOutRecs; i++)
  317.         if (!gsSHOutVars.outArray[i].inUse) {
  318.             *outRec = &gsSHOutVars.outArray[i];
  319.             return(noErr);
  320.         }
  321.     
  322.     return(kSHErrOutaChannels);
  323. }
  324.  
  325. //=======================================================================================
  326. //
  327. //    pascal void SHPlayCompletion(SndChannelPtr channel, SndCommand *command)
  328. //
  329. //    Summary:
  330. //        This routine is the playback callback routine we provide to the Sound Manager.
  331. //
  332. //    Scope:
  333. //        Private.
  334. //
  335. //    Parameters:
  336. //        channel        A pointer to the sound channel that is calling back.  It is calling
  337. //                    back because we queued up a callbackCmd.
  338. //        command        A pointer to the actual command that caused us to be called back.
  339. //                    This command happens to have important information (like the app's
  340. //                    A5, and a constant we can use to verify that this is a "real" call-
  341. //                    back, as opposed to one that has been erroneously generated by the
  342. //                    Sound Manager).
  343. //
  344. //    Returns:
  345. //        Nothing.
  346. //
  347. //    Operation:
  348. //        This routine first looks for our "completion signature."  This is how we know
  349. //        that the callback really means the sound has completed.  There is a bug in the
  350. //        Sound Manager that may cause callbacks that weren't specifically requested, and
  351. //        this constant allows us to distinguish our "real" callback from one that is a
  352. //        result of that bug.  If the callback is hip, then we set up A5 (so we can ref-
  353. //        erence our globals), and set the application's attention flag.  Also, we set
  354. //        the channel's userInfo field to a constant that SHIdle will recognize, so SHIdle
  355. //        will know the sound on that channel has completed, and that the channel can be
  356. //        freed.
  357. //
  358. //=======================================================================================
  359. pascal void SHPlayCompletion(SndChannelPtr channel, SndCommand *command)
  360. {
  361.     long    otherA5;
  362.     
  363.     // Look for our "callback signature" in the sound command.
  364.     if (command->param1 == kSHCompleteSig) {
  365.         otherA5 = SetA5(command->param2);    // Set up our A5
  366.         
  367.         channel->userInfo = kSHComplete;
  368.         *gsSHNeedsTime = true;                // Tell the app to give us an SHIdle call
  369.         
  370.         SetA5(otherA5);                        // Retore old A5
  371.     }
  372. }
  373.  
  374. //=======================================================================================
  375. //
  376. //    pascal void SHRecordCompletion(SPBPtr inParams)
  377. //
  378. //    Summary:
  379. //        This routine is the recording callback routine we provide to the Sound Manager.
  380. //
  381. //    Scope:
  382. //        Private.
  383. //
  384. //    Parameters:
  385. //        inParams        This points to the input sound parameter block that has completed
  386. //                        recording.  When we filled out the parameter block, we stuffed
  387. //                        the application A5 into userLong, which allows us to access our
  388. //                        globals while we're here.
  389. //
  390. //    Returns:
  391. //        Nothing.
  392. //
  393. //    Operation:
  394. //        When recording completes for any reason (error, consumed all the memory that was
  395. //        provided, abort, etc.) then the Sound Manager calls our callback routine.  This
  396. //        routine first grabs A5 from the SPB's userLong field and sets us up to use our
  397. //        globals.  Then, it sets the application's "Helper needs time" Boolean, and sets
  398. //        our internal flag that recording has completed (so SHIdle will know to close the
  399. //        recording device, etc.)
  400. //
  401. //=======================================================================================
  402. pascal void SHRecordCompletion(SPBPtr inParams)
  403. {
  404.     long    otherA5;
  405.     
  406.     otherA5 = SetA5(inParams->userLong);        // Set up our A5
  407.     
  408.     *gsSHNeedsTime = true;                        // Notify the app to give us time
  409.     gsSHInVars.recordComplete = true;            // Make a note to ourselves, too
  410.     
  411.     SetA5(otherA5);                                // Restore old A5
  412. }
  413.  
  414. //=======================================================================================
  415. //
  416. //    OSErr SHInitOutRec(SHOutPtr outRec, long refNum, Handle sound, char handleState)
  417. //
  418. //    Summary:
  419. //        This routine is used to fill out an SHOutRec and call SndNewChannel.
  420. //
  421. //    Scope:
  422. //        Private.
  423. //
  424. //    Parameters:
  425. //        outRec            A pointer to the SHOutRec we're filling out.
  426. //        refNum            The output reference number we'll give back to the caller.
  427. //        sound            A locked, non-purgeable handle to a (hopefully) valid sound.
  428. //        handleState        The original handle state, before the HLock and HNoPurge.  This
  429. //                        allows SHReleaseOutRec to properly reset the handle's flags when
  430. //                        playback is complete.
  431. //
  432. //    Returns:
  433. //        OSErr            Error results of SndNewChannel call, if an error occurred.
  434. //        noErr            Otherwise.
  435. //
  436. //    Operation:
  437. //        This routine is called to fill out a SHOutRec.  First, it clears the SndChannel
  438. //        within the SHOutRec to all zeros.  It then installs the default queue size, and
  439. //        calls the Sound Manager routine SndNewChannel.  If an error occurs, we return
  440. //        it right away.  If not, then we fill out the rest of the fields in the SHOutRec.
  441. //        Note that in the call to SndNewChannel, we specify NO SYNTHESIZER, and NO INIT-
  442. //        IALIZATION.  This is because the Helper is a "sound service," and has no freakin'
  443. //        idea what kind of sound the caller is going to try to play using this channel.
  444. //        So, we assume nothing.  Also note that we provide our completion routine,
  445. //        SHPlayCompletion, to SndNewChannel.
  446. //
  447. //=======================================================================================
  448. OSErr SHInitOutRec(SHOutPtr outRec, long refNum, Handle sound, char handleState)
  449. {
  450.     short            i;
  451.     OSErr            err;
  452.     SndChannelPtr    channel;
  453.     
  454.     // Initialize the sound channel inside outRec.  We'll clear the bytes to zero,
  455.     // install the proper queue size, then call SndNewChannel.
  456.     for (i = 0; i < sizeof(SndChannel); i++)
  457.         ((char *)&outRec->channel)[i] = 0;
  458.     outRec->channel.qLength = stdQLength;
  459.     channel = &outRec->channel;
  460.     err = SndNewChannel(&channel, kSHNoSynth, kSHNoInit, 
  461.         (SndCallBackProcPtr)SHPlayCompletion);
  462.     if (err != noErr)
  463.         return(err);
  464.     
  465.     // Initialize the rest of the record and return noErr.  Note that we only set the
  466.     // record's inUse flag if the SndNewChannel call was successful.
  467.     outRec->refNum = refNum;
  468.     outRec->sound = sound;
  469.     outRec->rate = 0;
  470.     outRec->handleState = handleState;
  471.     outRec->inUse = true;
  472.     outRec->paused = false;
  473.     return(noErr);
  474. }
  475.  
  476. //=======================================================================================
  477. //
  478. //    void SHReleaseOutRec(SHOutPtr outRec)
  479. //
  480. //    Summary:
  481. //        This routine "releases," or frees up an output record.
  482. //
  483. //    Scope:
  484. //        Private.
  485. //
  486. //    Parameters:
  487. //        outRec        A pointer to the output record we want to release.
  488. //
  489. //    Returns:
  490. //        Nothing.
  491. //
  492. //    Operation:
  493. //        If the output record's inUse flag is set, that means that SndNewChannel has been
  494. //        called for it.  In that case, we call SndDisposeChannel to allow the Sound Man-
  495. //        ager to dispose it's internal data structures for this channel.  Either way, if
  496. //        there's an associated sound, we check whether the sound is playing on any other
  497. //        channel, and if not, we reset it's handle flags.  Finally, we clear the record's
  498. //        inUse flag, thereby allowing it to be reused.
  499. //
  500. //=======================================================================================
  501. void SHReleaseOutRec(SHOutPtr outRec)
  502. {
  503.     short    i;
  504.     Boolean    found = false;
  505.     
  506.     // An SHOutRec's inUse flag only gets set if SndNewChannel has been called on the
  507.     // record's sound channel.  So if it is in use, we try a call to SndDisposeChannel,
  508.     // and ignore the error (what else can we do?)
  509.     if (outRec->inUse)
  510.         SndDisposeChannel(&outRec->channel, kSHQuietNow);
  511.  
  512.     // If this sound handle isn't being used by some other output record, kindly restore
  513.     // the original handle state.
  514.     if (outRec->sound != nil) {
  515.         for (i = 0; i < gsSHOutVars.numOutRecs && !found; i++)
  516.             if (&gsSHOutVars.outArray[i] != outRec && gsSHOutVars.outArray[i].inUse &&
  517.                     gsSHOutVars.outArray[i].sound == outRec->sound)
  518.                 found = true;
  519.         
  520.         if (!found)
  521.             HSetState(outRec->sound,outRec->handleState);
  522.     }
  523.     
  524.     outRec->inUse = false;
  525. }
  526.  
  527. //=======================================================================================
  528. //
  529. //    OSErr SHQueueCallback(SndChannel *channel)
  530. //
  531. //    Summary:
  532. //        This routine queues up a verifyable callback in the given sound channel.
  533. //
  534. //    Scope:
  535. //        Private:
  536. //
  537. //    Parameters:
  538. //        channel        The sound channel we want a callback from.
  539. //
  540. //    Returns:
  541. //        OSErr        Results of the SndDoCommand call.
  542. //
  543. //    Operation:
  544. //        This routine queues up a sound command in the given channel that will cause a
  545. //        callback.  This is how we'll know the sound completed.  In order to make the
  546. //        callback verifyable, we stuff kSHCompleteSig into param1.  We can test for this
  547. //        value within the callback routine.  Also, since the poor callback is called at
  548. //        interrupt time and can't count on its A5 world, we provide the application A5
  549. //        in param2.
  550. //
  551. //=======================================================================================
  552. OSErr SHQueueCallback(SndChannel *channel)
  553. {
  554.     SndCommand    command;
  555.  
  556.     command.cmd = callBackCmd;
  557.     command.param1 = kSHCompleteSig;        // To make the callback verifyable.
  558.     command.param2 = SetCurrentA5();        // So the callback routine can access globals.
  559.     return(SndDoCommand(channel, &command, kSHWait));
  560. }
  561.  
  562. //=======================================================================================
  563. //
  564. //    OSErr SHBeginPlayback(SHOutPtr outRec)
  565. //
  566. //    Summary:
  567. //        This routine begins playback of the sound that's installed in the given SHOutRec.
  568. //
  569. //    Scope:
  570. //        Private.
  571. //
  572. //    Parameters:
  573. //        outRec        The output record that we want to start playback on.
  574. //
  575. //    Returns:
  576. //        OSErr        Error results of SndPlay, if an error occurred.
  577. //        noErr        Otherwise.
  578. //
  579. //    Operation:
  580. //        This routine calls SndPlay (asynchronously) for the sound that is installed in
  581. //        the given output record.  This begins playback.  Immediately following that, we
  582. //        queue up a callback, so that when the sound that we just start completes, we'll
  583. //        get a callback (to SHPlayCompletion), and we'll know that the channel needs to
  584. //        be released.
  585. //
  586. //    IMPORTANT:
  587. //        This routine is called from SHPlayByID, and SHPlayByHandle when a sound handle is
  588. //        provided.  The purpose of these routines is to trigger a sound, and if you call
  589. //        SHPlayByID or SHPlayByHandle that way, DON'T use SHGetChannel to get the sound
  590. //        channel Helper is using to play the sound, then subsequently call SndPlay your-
  591. //        self to play some other sound.  Why not?  There is a bug in pre-7.0 Systems that
  592. //        causes a crash if more than one SndPlay call is made on the same channel.  Helper
  593. //        will never do this on its own, and you shouldn't either. If you want a sound
  594. //        channel that you want to send commands to, call SHPlayByHandle with a nil handle,
  595. //        then call SHGetChannel to retreive a pointer to the channel.
  596. //
  597. //=======================================================================================
  598. OSErr SHBeginPlayback(SHOutPtr outRec)
  599. {
  600.     OSErr    err;
  601.     
  602.     // First, initiate playback.  If an error occurs, return it immediately.
  603.     err = SndPlay(&outRec->channel, outRec->sound, kSHAsync);
  604.     if (err != noErr)
  605.         return(err);
  606.     
  607.     // Playback started okay.  Let's queue up a callback command so we'll know when
  608.     // the sound is finished.
  609.     SHQueueCallback(&outRec->channel);        // ignore error (what can we do?)
  610.     return(noErr);
  611. }
  612.  
  613. //=======================================================================================
  614. //
  615. //    char SHGetState(Handle snd)
  616. //
  617. //    Summary:
  618. //        This routine is a local replacement for HGetState which tries to find snd in an
  619. //        existing output record.
  620. //
  621. //    Scope:
  622. //        Private:
  623. //
  624. //    Parameters:
  625. //        snd            The handle we want the handle state for
  626. //
  627. //    Returns:
  628. //        A char representing the handle flags (either currently or from some existing
  629. //        output record).
  630. //
  631. //    Operation:
  632. //        This routine searches the output record array for an output record that is both
  633. //        in use AND has a "sound" field equal to the parameter snd.  What this means is
  634. //        that we've found an output record that is currently playing snd.  If we find
  635. //        such a record, we return the "handleState" field of that output record.  If no
  636. //        such record is found, then we return the results of HGetState(snd).  The reason
  637. //        we need this is that you could re-trigger a sound (that is, play the same sound
  638. //        simultaneously on more than one Helper output channel).  In such a case, the
  639. //        first SHPlayByID or (ByHandle) call would get the actual handle state (from
  640. //        HGetState).  If another SHPlayByID call came in while the original was still
  641. //        playing, the handleState from the existing output record would be retured.  This
  642. //        way, the second Play doesn't save a "locked" state and restore to a locked state
  643. //        when the sound has completed.
  644. //
  645. //=======================================================================================
  646. char SHGetState(Handle snd)
  647. {
  648.     short    i;
  649.     
  650.     // Look for an output record that has snd for a sound.  If one is found, grab and
  651.     // return its handleState instead of the handle's current flags.
  652.     for (i = 0; i < gsSHOutVars.numOutRecs; i++)
  653.         if (gsSHOutVars.outArray[i].inUse && gsSHOutVars.outArray[i].sound == snd)
  654.             return(gsSHOutVars.outArray[i].handleState);
  655.     
  656.     return(HGetState(snd));
  657. }
  658.  
  659. //=======================================================================================
  660. //
  661. //    pascal OSErr SHPlayByID(short resID, long *refNum)
  662. //
  663. //    Summary:
  664. //        This routine begins asynchronous playback of the 'snd ' resource with ID resID.
  665. //
  666. //    Scope:
  667. //        Public.
  668. //
  669. //    Parameters:
  670. //        resID        The resource ID of the 'snd ' resource the caller wants to play back.
  671. //        refNum        A pointer to where to store the output reference number.  THIS IS
  672. //                    OPTIONAL.  If nil is specified, the refNum is not returned.
  673. //
  674. //    Returns:
  675. //        ResError()                If the GetResource failed, and ResError gave an error.
  676. //        resNotFound                If the GetResource failed, but ResError was noErr.
  677. //        kSHErrOutaChannels        If the SHNewOutRec call failed.
  678. //        OSErr                    If the SHInitOutRec call failed.
  679. //        OSErr                    If the SHBeginPlayback call failed.
  680. //        noErr                    Otherwise.
  681. //
  682. //    Operation:
  683. //        This routine plays the 'snd ' resource referred to by ID resID.  First, we try
  684. //        to load the sound resource.  If successful, we note the handle state of the
  685. //        sound handle, and set it to be nonpurgeable (because we don't want subsequent
  686. //        operations, namely the SndNewChannel call that happens in SHInitOutRec, to wipe
  687. //        out the sound we so carefully read into memory).  Then we get a reference number
  688. //        and a pointer to the next free output record.  If successful, we initialize the
  689. //        output record (and open the sound channel) with SHInitOutRec.  If successful,
  690. //        we move the sound handle as high in the heap as we can (to help avoid fragmen-
  691. //        tation), and lock it.  Then we call SHBeginPlayback to start the sound playing
  692. //        and queue up a callback so we'll know when it's done.  If successful, we return
  693. //        the reference number (if the caller wants it).
  694. //
  695. //    IMPORTANT:
  696. //        DO NOT start a sound playing with SHPlayByID, get it's channel with SHGetChannel,
  697. //        and then do another SndPlay on that channel!  This will crash on pre-7.0 systems.
  698. //        If you want a channel, use SHPlayByHandle with a nil handle.  See the comments
  699. //        for SHPlayByHandle and SHBeginPlayback.
  700. //        
  701. //=======================================================================================
  702. pascal OSErr SHPlayByID(short resID, long *refNum)
  703. {
  704.     Handle        sound;
  705.     char        oldhandleState;
  706.     short        ref;
  707.     OSErr        err;
  708.     SHOutPtr    outRec;
  709.     
  710.     // First, try to get the caller's 'snd ' resource.  If we can't return ResError().
  711.     // If we DO get the sound, save it's flags, then set it to be nonpurgeable.  This
  712.     // is because some of the Sound Manager stuff below may cause memory allocation,
  713.     // which could cause the sound to be purged.  We don't want that, since we're
  714.     // going to start playing it real soon.
  715.     sound = GetResource(soundListRsrc, resID);
  716.     if (sound == nil) {
  717.         err = ResError();
  718.         if (err == noErr)
  719.             err = resNotFound;
  720.         return(err);
  721.     }
  722.     oldhandleState = SHGetState(sound);
  723.     HNoPurge(sound);
  724.         
  725.     // Now let's get a reference number and an output record.
  726.     ref = SHNewRefNum();
  727.     err = SHNewOutRec(&outRec);
  728.     if (err != noErr) {
  729.         HSetState(sound, oldhandleState);
  730.         return(err);
  731.     }
  732.     
  733.     // Now let's fill in the output record with all the pertinent information.  This
  734.     // routine also initializes the sound channel and flags outRec as "in use."
  735.     err = SHInitOutRec(outRec, ref, sound, oldhandleState);
  736.     if (err != noErr) {
  737.         HSetState(sound, oldhandleState);
  738.         SHReleaseOutRec(outRec);
  739.         return(err);
  740.     }
  741.     
  742.     // At this point, we're in pretty good shape.  We've got a reference number, an
  743.     // initialized output record, and the sound handle.  Let's party.
  744.     MoveHHi(sound);
  745.     HLock(sound);
  746.     err = SHBeginPlayback(outRec);
  747.     if (err != noErr) {
  748.         HSetState(sound, oldhandleState);
  749.         SHReleaseOutRec(outRec);
  750.         return(err);
  751.     } else {
  752.         if (refNum != nil)            // refNum is optional -- the caller may not want it
  753.             *refNum = ref;
  754.         return(noErr);
  755.     }
  756. }
  757.  
  758. //=======================================================================================
  759. //
  760. //    pascal OSErr SHPlayByHandle(Handle sound, long *refNum)
  761. //
  762. //    Summary:
  763. //        This routine begins asynchronous playback of a sound provided in a handle.
  764. //
  765. //    Scope:
  766. //        Public.
  767. //
  768. //    Parameters:
  769. //        sound        A handle to the sound the caller wants to play.  This may optionally
  770. //                    be nil, indicating that the sound channel should be opened, but no
  771. //                    SndPlay call should be made.  If a caller does this, he usually calls
  772. //                    SHGetChannel to get a pointer to the sound channel, so he can send
  773. //                    sound commands to the channel.
  774. //        refNum        A pointer to where to store the output reference number.  THIS IS
  775. //                    OPTIONAL.  If nil is passed, the reference number is not returned.
  776. //
  777. //    Returns:
  778. //        kSHErrOutaChannels        If the SHNewOutRec call failed.
  779. //        OSErr                    If the SHInitOutRec call failed.
  780. //        OSErr                    If the SHBeginPlayback call failed.
  781. //        noErr                    Otherwise.
  782. //
  783. //    Operation:
  784. //        If a handle is provided, we set it to be nonpurgeable so that subsequent oper-
  785. //        ations don't blow it away, and we note it's current handle state.  Then, we get
  786. //        a reference number and a pointer to a free output record.  If successful, we
  787. //        initialize the output record, thereby opening the sound channel.  Then, if a
  788. //        sound was provided, we move it high, lock it, and call SHBeginPlayback to begin
  789. //        asynchronous playback and queue up a callback.  Finally, we return the reference
  790. //        number if the caller wants it.  If the sound wasn't provided (i.e. nil), every-
  791. //        thing is the same except there's no SHBeginPlayback call.
  792. //
  793. //    IMPORTANT:
  794. //        DO NOT start a sound handle playing with SHPlayByHandle, get it's channel with
  795. //        SHGetChannel, and then do another SndPlay on that channel!  This will crash on
  796. //        pre-7.0 systems. If you want a channel, use SHPlayByHandle with a _NIL_ handle.
  797. //        See the comments for SHBeginPlayback.
  798. //        
  799. //=======================================================================================
  800. pascal OSErr SHPlayByHandle(Handle sound, long *refNum)
  801. {
  802.     char        oldhandleState;
  803.     short        ref;
  804.     OSErr        err;
  805.     SHOutPtr    outRec;
  806.     
  807.     // Save sound handle's flags, then set it to be nonpurgeable.  This is because some
  808.     // of the Sound Manager stuff below may cause memory allocation, which could cause
  809.     // the handle to be purged.  We don't want that, since we're going to start playing
  810.     // it real soon.  If the caller gave us nil for a sound handle, that means he's
  811.     // really just interested in having the sound channel.  So, we go on our merry way
  812.     // without a sound handle.
  813.     if (sound != nil) {
  814.         oldhandleState = SHGetState(sound);
  815.         HNoPurge(sound);
  816.     } else oldhandleState = 0;
  817.         
  818.     // Now, let's get a reference number and an output record.
  819.     ref = SHNewRefNum();
  820.     err = SHNewOutRec(&outRec);
  821.     if (err != noErr) {
  822.         if (sound != nil)
  823.             HSetState(sound, oldhandleState);
  824.         return(err);
  825.     }
  826.     
  827.     // Now let's fill in the output record with all the pertinent information.  This
  828.     // routine also initializes the sound channel and flags outRec as "in use."
  829.     err = SHInitOutRec(outRec, ref, sound, oldhandleState);
  830.     if (err != noErr) {
  831.         if (sound != nil)
  832.             HSetState(sound, oldhandleState);
  833.         SHReleaseOutRec(outRec);
  834.         return(err);
  835.     }
  836.     
  837.     // At this point, we're in pretty good shape.  We've got a reference number, an
  838.     // initialized output record, and the sound handle.  Let's get whacky.
  839.     if (sound != nil) {            // if we've got a sound, lock and begin playback
  840.         MoveHHi(sound);
  841.         HLock(sound);
  842.         err = SHBeginPlayback(outRec);
  843.         if (err != noErr) {
  844.             HSetState(sound, oldhandleState);
  845.             SHReleaseOutRec(outRec);
  846.             return(err);
  847.         } else {
  848.             if (refNum != nil)        // refNum is optional -  the caller may not want it
  849.                 *refNum = ref;
  850.             return(noErr);
  851.         }
  852.     } else {                        // if there's no sound, go ahead and return noErr
  853.         if (refNum != nil)            // refNum is optional -  the caller may not want it
  854.             *refNum = ref;
  855.         return(noErr);
  856.     }
  857. }
  858.  
  859. //=======================================================================================
  860. //
  861. //    SHOutPtr SHOutRecFromRefNum(long refNum)
  862. //
  863. //    Summary:
  864. //        This routine finds that SHOutRec that is associated with a given refNum, if any.
  865. //
  866. //    Scope:
  867. //        Private.
  868. //
  869. //    Parameters:
  870. //        refNum        The output reference number in question.
  871. //
  872. //    Returns:
  873. //        A pointer to the associated SHOutRec, if any, or nil, if none was found with a
  874. //        reference number matching refNum.
  875. //
  876. //    Operation:
  877. //        This handy routine searches the output record array looking for an output record
  878. //        that has the given reference number.  If one is found, a pointer to it is
  879. //        returned.  If not, then nil is returned.
  880. //
  881. //=======================================================================================
  882. SHOutPtr SHOutRecFromRefNum(long refNum)
  883. {
  884.     short    i;
  885.     
  886.     // Search for the specified refNum
  887.     for (i = 0; i < gsSHOutVars.numOutRecs; i++)
  888.         if (gsSHOutVars.outArray[i].inUse && gsSHOutVars.outArray[i].refNum == refNum)
  889.             break;
  890.     
  891.     // If we found it, return a pointer to that record, otherwise, nil.
  892.     if (i == gsSHOutVars.numOutRecs)
  893.         return(nil);
  894.     else return(&gsSHOutVars.outArray[i]);
  895. }
  896.  
  897. //=======================================================================================
  898. //
  899. //    void SHPlayStopByRec(SHOutPtr outRec)
  900. //
  901. //    Summary:
  902. //        This routine stops sound playback on the channel associated with the given
  903. //        output record.
  904. //
  905. //    Scope:
  906. //        Private.
  907. //
  908. //    Parameters:
  909. //        outRec        A pointer to the output record whose sound should be stopped.
  910. //
  911. //    Returns:
  912. //        Nothing.
  913. //
  914. //    Operation:
  915. //        This routine sends two immediate sound commands to the channel in the given
  916. //        output record.  The flushCmd gets rid of any unprocessed commands from the
  917. //        queue subsequent to the one currently being processed.  The quietCmd, when sent
  918. //        with SndDoImmediate, immediately quiets the channel.  Note that there might not
  919. //        be any synthesizer yet associate with this channel, and in that case, these
  920. //        commands are just eaten by the Sound Manager.
  921. //
  922. //=======================================================================================
  923. void SHPlayStopByRec(SHOutPtr outRec)
  924. {
  925.     SndCommand    cmd;
  926.  
  927.     // Dump the rest of the commands in the queue (including our callbackCmd).
  928.     cmd.cmd = flushCmd;
  929.     cmd.param1 = 0;
  930.     cmd.param2 = 0;
  931.     SndDoImmediate(&outRec->channel, &cmd);
  932.     
  933.     // Shut up this minute!  Go to your room!  No dessert tonite for you, little boy.
  934.     cmd.cmd = quietCmd;
  935.     cmd.param1 = 0;
  936.     cmd.param2 = 0;
  937.     SndDoImmediate(&outRec->channel, &cmd);
  938.     
  939.     // It is now safe to just manually dump our channel (we'll just skip the whole
  940.     // callback thing in this case).
  941.     SHReleaseOutRec(outRec);
  942. }
  943.  
  944. //=======================================================================================
  945. //
  946. //    pascal OSErr SHPlayStop(long refNum)
  947. //
  948. //    Summary:
  949. //        This routine stops playback on the output record referred to by refNum.
  950. //
  951. //    Scope:
  952. //        Public.
  953. //
  954. //    Parameters:
  955. //        refNum        The output reference number of the sound the caller wants stopped.
  956. //
  957. //    Returns:
  958. //        kSHErrBadRefNum        If the reference number does not refer to any current output
  959. //                            record.  (Note that this is not necessarily bad.  If they
  960. //                            try to stop a sound that has already stopped by its own
  961. //                            accord, this error will be returned.  Usually you can call
  962. //                            this routine and ignore the error.)
  963. //        noErr                Otherwise.
  964. //
  965. //    Operation:
  966. //        This routine calls SHOutRecFromRefNum to try to find the output record that is
  967. //        associated with refNum.  If one is found, we call SHPlayStopByRec to stop
  968. //        playback for that output record.
  969. //
  970. //=======================================================================================
  971. pascal OSErr SHPlayStop(long refNum)
  972. {
  973.     SHOutPtr    outRec;
  974.     
  975.     // Look for the associated output record.
  976.     outRec = SHOutRecFromRefNum(refNum);
  977.     
  978.     // If we found it, call SHPlayStopByRec to stop playback.
  979.     if (outRec != nil) {
  980.         SHPlayStopByRec(outRec);
  981.         return(noErr);
  982.     } else return(kSHErrBadRefNum);
  983. }
  984.  
  985. //=======================================================================================
  986. //
  987. //    pascal OSErr SHPlayStopAll(void)
  988. //
  989. //    Summary:
  990. //        This routine stops all sound that the Helper initiated.
  991. //
  992. //    Scope:
  993. //        Public.
  994. //
  995. //    Parameters:
  996. //        None.
  997. //
  998. //    Returns:
  999. //        noErr        This may return something more interesting in the future.
  1000. //
  1001. //    Operation:
  1002. //        This routine iterates through all the output records looking for records that
  1003. //        are in use.  When an in-use record is found, playback on that record is stopped
  1004. //        by calling SHPlayStopByRec.  Errors are ignored.
  1005. //
  1006. //=======================================================================================
  1007. pascal OSErr SHPlayStopAll(void)
  1008. {
  1009.     short    i;
  1010.     
  1011.     // Look for output records that are in use and stop their playback with
  1012.     // SHPlayStopByRec.
  1013.     for (i = 0; i < gsSHOutVars.numOutRecs; i++)
  1014.         if (gsSHOutVars.outArray[i].inUse)
  1015.             SHPlayStopByRec(&gsSHOutVars.outArray[i]);
  1016.     
  1017.     return(noErr);
  1018. }
  1019.  
  1020. //=======================================================================================
  1021. //
  1022. //    pascal OSErr SHPlayPause(long refNum)
  1023. //
  1024. //    Summary:
  1025. //        This routine pauses playback of sound associated with refNum.
  1026. //
  1027. //    Scope:
  1028. //        Public.
  1029. //
  1030. //    Parameters:
  1031. //        refNum        The output reference number of the sound the caller wants paused.
  1032. //
  1033. //    Returns:
  1034. //        OSErr                If a SndDoImmediate fails.
  1035. //        kSHErrBadRefNum        If the given reference number is not associated with any
  1036. //                            current output record.
  1037. //        kSHErrAlreadyPaused    If the sound is already paused.
  1038. //
  1039. //    Operation:
  1040. //        For a sound like "Simple beep," which is a long sequence of sound commands,
  1041. //        pausing a sound means "pausing sound command queue processing," and is performed
  1042. //        with the pauseCmd.  Sampled sounds, like "Wild Eep," usually consist of a single
  1043. //        bufferCmd to play back the sampled sound.  The pauseCmd is ineffective with
  1044. //        sampled sounds because the sound is paused after the current command is processed
  1045. //        (the bufferCmd), so the entire sound would be played.  This is rarely what the
  1046. //        caller wants.  So, we've got a little trick in here to pause sampled sounds.  If
  1047. //        you set a sampled sound's sample playback rate to zero, it effectively pauses the
  1048. //        sampled sound in its tracks, mid-bufferCmd (which is what the caller probably
  1049. //        wants).
  1050. //
  1051. //        There is really no officially sanctioned way to know whether a sound is command-
  1052. //        type or sampled without parsing the sound.  However, any synthesizer that returns
  1053. //        a non-zero rate from a getRateCmd call will be able to understand a rateCmd.  So
  1054. //        we try a getRateCmd, and if we get a non-zero rate, send a rateCmd to set the
  1055. //        playback rate to zero.  If we get zero from the getRateCmd, we assume that the
  1056. //        synthesizer cannot understand the getRateCmd, and instead use a pauseCmd to pause
  1057. //        the sound.  This is the only offically sanctioned universal method of pausing any
  1058. //        sound.
  1059. //
  1060. //        If the sound was successfully paused, the output record's paused flag is set.
  1061. //
  1062. //=======================================================================================
  1063. pascal OSErr SHPlayPause(long refNum)
  1064. {
  1065.     SHOutPtr    outRec;
  1066.     SndCommand    cmd;
  1067.     OSErr        err;
  1068.     
  1069.     outRec = SHOutRecFromRefNum(refNum);
  1070.     if (outRec != nil) {
  1071.         // Don't bother with this if we're already paused.
  1072.         if (outRec->paused)
  1073.             return(kSHErrAlreadyPaused);
  1074.         
  1075.         // Get the current playback rate for this sound.
  1076.         cmd.cmd = getRateCmd;
  1077.         cmd.param1 = 0;
  1078.         cmd.param2 = &outRec->rate;
  1079.         err = SndDoImmediate(&outRec->channel, &cmd);
  1080.         if (err != noErr)
  1081.             return(err);
  1082.         
  1083.         // Now pause with either a rateCmd or a pauseCmd, as appropriate
  1084.         cmd.param1 = 0;
  1085.         cmd.param2 = 0;
  1086.         if (outRec->rate != 0) {
  1087.             // If we get something non-zero, it's safe to assume that whatever
  1088.             // synthesizer we're talking to will be able to understand a rateCmd to
  1089.             // restore the rate (probably the sampled synthesizer).  To pause the
  1090.             // sound, we'll set the rate to zero.
  1091.             cmd.cmd = rateCmd;
  1092.             err = SndDoImmediate(&outRec->channel, &cmd);
  1093.             if (err != noErr)
  1094.                 return(err);
  1095.         } else {
  1096.             // This synthesizer doesn't understand rateCmds.  So instead we'll just
  1097.             // pause command queue processing with a pauseCmd.  This is how command-type
  1098.             // sounds (e.g. Simple Beep) are paused.
  1099.             cmd.cmd = pauseCmd;
  1100.             err = SndDoImmediate(&outRec->channel, &cmd);
  1101.             if (err != noErr)
  1102.                 return(err);
  1103.         }
  1104.  
  1105.         outRec->paused = true;
  1106.         return(noErr);
  1107.     } else return(kSHErrBadRefNum);
  1108. }
  1109.  
  1110. //=======================================================================================
  1111. //
  1112. //    pascal OSErr SHPlayContinue(long refNum)
  1113. //
  1114. //    Summary:
  1115. //        This routine continues playback of a previously paused sound.
  1116. //
  1117. //    Scope:
  1118. //        Public.
  1119. //
  1120. //    Parameters:
  1121. //        refNum        The refNum of the sound the caller wants playback continued on.  This
  1122. //                    should be the refNum of a sound that was previously paused with
  1123. //                    SHPlayPause.
  1124. //
  1125. //    Returns:
  1126. //        OSErr                    If the SndDoImmediate fails.
  1127. //        kSHErrBadRefNum            If the refNum doesn't refer to any current output record.
  1128. //        kSHErrAlreadyContinued    If the sound is not paused.
  1129. //
  1130. //    Operation:
  1131. //        First SHPlayContinue gets a pointer to the output record (if any) that refNum
  1132. //        refers to.  If found, and that sound is paused, we check the output record's
  1133. //        rate field.  If non-zero, then the sound was paused with rateCmd, so we send 
  1134. //        another rateCmd to restore its playback rate.  Otherwise, we send a resumeCmd
  1135. //        (to resume command-queue processing).  (See the comments for SHPlayPause for
  1136. //        details on the two methods of pausing sound.)  If the resumeCmd is successful,
  1137. //        we clear the output record's paused flag.
  1138. //
  1139. //=======================================================================================
  1140. pascal OSErr SHPlayContinue(long refNum)
  1141. {
  1142.     SHOutPtr    outRec;
  1143.     SndCommand    cmd;
  1144.     OSErr        err;
  1145.     
  1146.     outRec = SHOutRecFromRefNum(refNum);
  1147.     if (outRec != nil) {
  1148.         // Don't even bother with this stuff if the channel isn't paused.
  1149.         if (!outRec->paused)
  1150.             return(kSHErrAlreadyContinued);
  1151.         
  1152.         // Now continue playback with a rateCmd or a resumeCmd, as appropriate.
  1153.         cmd.param1 = 0;
  1154.         if (outRec->rate != 0) {
  1155.             // Resume sampled sound playback by restoring the synthesizer's playback
  1156.             // rate with a rateCmd.
  1157.             cmd.cmd = rateCmd;
  1158.             cmd.param2 = outRec->rate;
  1159.             err = SndDoImmediate(&outRec->channel, &cmd);
  1160.             if (err != noErr)
  1161.                 return(err);
  1162.         } else {
  1163.             // Resume sound queue processing with a resumeCmd.
  1164.             cmd.cmd = resumeCmd;
  1165.             cmd.param2 = 0;
  1166.             err = SndDoImmediate(&outRec->channel, &cmd);
  1167.             if (err != noErr)
  1168.                 return(err);
  1169.         }
  1170.         
  1171.         outRec->paused = false;
  1172.         return(noErr);
  1173.     } else return(kSHErrBadRefNum);
  1174. }
  1175.  
  1176. //=======================================================================================
  1177. //
  1178. //    pascal SHPlayStat SHPlayStatus(long refNum)
  1179. //
  1180. //    Summary:
  1181. //        This routine returns a status value for the sound associated with refNum.
  1182. //
  1183. //    Scope:
  1184. //        Public.
  1185. //
  1186. //    Parameters:
  1187. //        refNum        The sound for which the caller wishes status information.
  1188. //
  1189. //    Returns:
  1190. //        shpError = -1        If refNum has never been used (and is therefore invalid).
  1191. //        shpFinished = 0        If the sound associated with refNum has completed.
  1192. //        shpPaused = 1        If the sound associated with refNum is currently paused.
  1193. //        shpPlaying = 2        If the sound associated with refNum is currently playing.
  1194. //
  1195. //    Operation:
  1196. //        First we check to see if refNum is greater than or equal to our next output
  1197. //        reference number.  If it is, then this reference number is definitely invalid,
  1198. //        so we return shpError.  Otherwise, we look refNum up with SHOutRecFromRefNum.
  1199. //        If no record is found (but we know that refNum has been used in the past), we
  1200. //        can assume that the sound has completed, and return shpFinished.  Otherwise,
  1201. //        the sound is currently playing or is paused, so we return either shpPaused or
  1202. //        shpPlaying based on the value of the output record's paused flag.
  1203. //
  1204. //=======================================================================================
  1205. pascal SHPlayStat SHPlayStatus(long refNum)
  1206. {
  1207.     SHOutPtr    outRec;
  1208.     
  1209.     if (refNum >= gsSHOutVars.nextRef)
  1210.         return(shpError);
  1211.     else {
  1212.         outRec = SHOutRecFromRefNum(refNum);
  1213.     
  1214.         if (outRec != nil) {
  1215.             // We found an SHOutRec for the guy's ref num, (so it's in use).
  1216.             return((outRec->paused) ? shpPaused : shpPlaying);
  1217.         } else {
  1218.             // Although we've used the reference number in the past, it's not in use, so
  1219.             // we can assume whatever sound it was associated has since stopped.  So,
  1220.             // we'll return shpFinished in this case.
  1221.             return(shpFinished);
  1222.         }
  1223.     }
  1224. }
  1225.  
  1226. //=======================================================================================
  1227. //
  1228. //    pascal OSErr SHGetChannel(long refNum, SndChannelPtr *channel)
  1229. //
  1230. //    Summary:
  1231. //        This routine allows the caller to retrieve a pointer to the sound channel that
  1232. //        is associated with the given refNum.
  1233. //
  1234. //    Scope:
  1235. //        Public.
  1236. //
  1237. //    Parameters:
  1238. //        refNum        The sound for which the caller wants to retrieve a sound channel
  1239. //                    pointer.
  1240. //        channel        A pointer to a SndChannelPtr.  This VAR parameter is where the sound
  1241. //                    channel address is stored if it is found.
  1242. //
  1243. //    Returns:
  1244. //        kSHErrBadRefNum        If refNum doesn't refer to any current output record.
  1245. //        noErr                Otherwise.
  1246. //
  1247. //    Operation:
  1248. //        This routine is provided to allow more advanced callers to have access to the
  1249. //        sound channel associated with a reference number.  This could be useful, for
  1250. //        instance, if the caller wanted to send sound commands to the channel, and only
  1251. //        use the Helper to manage the channel (but not the sound).  A good example of
  1252. //        this is continuous background music.  You make a sound with a soundCmd and a
  1253. //        loop.  Then you open a channel by doing a SHPlayByHandle(nil, &ref), then get
  1254. //        the channel pointer by calling SHGetChannel, manually PlaySnd the background
  1255. //        music sound (which should contain a soundCmd to install the music as a voice),
  1256. //        then send a freqCmd to start the music playing.  It'll keep looping until a
  1257. //        quietCmd comes along.  (SEE NOTE BELOW.)
  1258. //
  1259. //    IMPORTANT:
  1260. //        If you use the above-described technique to provide looped background sound, it
  1261. //        is important to note that when you change the background music (e.g. from one
  1262. //        song to the next), you should SHPlayStop the channel, and allocate a new channel
  1263. //        with new calls to SHPlayByHandle(nil, &ref)/SHGetChannel.  DO NOT make another
  1264. //        SndPlay call on the same channel to change the sound, because this will crash on
  1265. //        pre-7.0 Systems.
  1266. //
  1267. //=======================================================================================
  1268. pascal OSErr SHGetChannel(long refNum, SndChannelPtr *channel)
  1269. {
  1270.     SHOutPtr    outRec;
  1271.     
  1272.     // Look for the output record associated with refNum.
  1273.     outRec = SHOutRecFromRefNum(refNum);
  1274.     
  1275.     // If we found one, return a pointer to the sound channel.
  1276.     if (outRec != nil) {
  1277.         *channel = &outRec->channel;
  1278.         return(noErr);
  1279.     } else return(kSHErrBadRefNum);
  1280. }
  1281.  
  1282. //=======================================================================================
  1283. //
  1284. //    OSErr SHGetDeviceSettings(long inRefNum, short *numChannels, Fixed *sampleRate,
  1285. //        short *sampleSize, OSType *compType)
  1286. //
  1287. //    Summary:
  1288. //        This routine gets several parameters from an open sound input device.
  1289. //
  1290. //    Scope:
  1291. //        Private.
  1292. //
  1293. //    Parameters:
  1294. //        inRefNum        The sound input device's input reference number.
  1295. //        numChannels        A VAR parameter in which the number of channels is returned.
  1296. //        sampleRate        A VAR parameter in which the sample rate (in Hz) is returned.
  1297. //        sampleSize        A VAR parameter in which the number of bits/sample is returned.
  1298. //        compType        A VAR parameter in which the compression type is returned.
  1299. //
  1300. //    Returns:
  1301. //        OSErr            If any of the SPBGetDeviceInfo calls fail.
  1302. //        noErr            Otherwise.
  1303. //
  1304. //    Operation:
  1305. //        This routine does four SPBGetDeviceInfo calls to retrieve the number of channels
  1306. //        the sample rate, the sample size, and the compression type for the input device
  1307. //        referred to by inRefNum.  This routine is almost verbatim out of Inside Macintosh
  1308. //        Volume 6.
  1309. //
  1310. //=======================================================================================
  1311. OSErr SHGetDeviceSettings(long inRefNum, short *numChannels, Fixed *sampleRate,
  1312.     short *sampleSize, OSType *compType)
  1313. {
  1314.     OSErr    err;
  1315.     
  1316.     // Hit on that sound input device.
  1317.     err = SPBGetDeviceInfo(inRefNum, siNumberChannels, (Ptr)numChannels);
  1318.     if (err != noErr)
  1319.         return(err);
  1320.     err = SPBGetDeviceInfo(inRefNum, siSampleRate, (Ptr)sampleRate);
  1321.     if (err != noErr)
  1322.         return(err);
  1323.     err = SPBGetDeviceInfo(inRefNum, siSampleSize, (Ptr)sampleSize);
  1324.     if (err != noErr)
  1325.         return(err);
  1326.     err = SPBGetDeviceInfo(inRefNum, siCompressionType, (Ptr)compType);
  1327.     return(err);
  1328. }
  1329.  
  1330. //=======================================================================================
  1331. //
  1332. //    pascal OSErr SHRecordStart(short maxK, OSType quality, Boolean *doneFlag)
  1333. //
  1334. //    Summary:
  1335. //        This routine initiates asynchronous sound recording.
  1336. //
  1337. //    Scope:
  1338. //        Public.
  1339. //
  1340. //    Parameters:
  1341. //        maxK        The amount of memory (in 1024-byte chunks) the caller wishes to
  1342. //                    preallocate for the user to record into.
  1343. //        quality        One of the standard Macintosh Sound Input Manager qualities: 'good',
  1344. //                    'betr', or 'best'.
  1345. //        doneFlag    A pointer to a Boolean by which the Helper will inform the caller
  1346. //                    that recording has finished and an SHGetRecordedSound call is in
  1347. //                    order.  If nil, then the caller will not be directly informed when
  1348. //                    recording is complete, but will instead have to call SHRecordStatus
  1349. //                    to find out.
  1350. //
  1351. //    Returns:
  1352. //        OSErr        If any of the stages fail.
  1353. //        noErr        Otherwise.
  1354. //
  1355. //    Operation:
  1356. //        This routine initiates asynchronous recording.  There are eight stages, each
  1357. //        of which could fail.  So, each state checks that the previous stage was success-
  1358. //        ful, so errors fall through the bottom.  Along the way, the local Booleans
  1359. //        deviceOpened and allocated are set when the sound input device is opened and
  1360. //        the sound input buffer is allocated, respectively.  If one or more of these flags
  1361. //        is set at the end of the routine AND there's been an error, then device closure/
  1362. //        deallocation is performed as required.  The stages are as follows:
  1363. //
  1364. //            1. Open the sound input device.
  1365. //            2. Ask the device if it can do asynchronous recording.
  1366. //            3. Allocate the sound input buffer, as specified by the maxK parameter.
  1367. //            4. Turn on metering and set the recording quality as specified by the
  1368. //               quality parameter.
  1369. //            5. The fifth stage is to grab (and save inside the gsInVars structure) the
  1370. //               default number of channels, sample rate, sample size, and compression
  1371. //               type.  We'll use the saved values later when we go to install a more
  1372. //               accurate header into the sound, at completion time.
  1373. //            6. Create a sound header in the sound input buffer.
  1374. //            7. Fill out the sound input parameter block inPB.  Note that we put the
  1375. //               application A5 into the userLong field of the parameter block, so that
  1376. //               SHRecordCompletion can access our globals.  Also note that
  1377. //               SHRecordCompletion is installed directly as the callback routine.  This
  1378. //               stage cannot fail, and sets err to noErr.
  1379. //            8. The eighth and final stage is to set various flags such that we know
  1380. //               we're recording, and calls SPBRecord to initiate the asynchronous
  1381. //               recording process.  The reason we set our flags before we make the
  1382. //               SPBRecord call is to avoid a "race" condition, where the recording could
  1383. //               (theoretically) complete virtually immediately and our callback routine
  1384. //               would get called before the flags were set up, thus confusing it.  To
  1385. //               avoid this, set the flags first, then the error handler code can reset
  1386. //               them if the recording failed.
  1387. //
  1388. //        If an error occurred along the way, the sound input device may be closed, and/or
  1389. //        the sound input buffer may be deallocated.
  1390. //
  1391. //=======================================================================================
  1392. pascal OSErr SHRecordStart(short maxK, OSType quality, Boolean *doneFlag)
  1393. {
  1394.     Boolean    deviceOpened = false;
  1395.     Boolean    allocated = false;
  1396.     
  1397.     OSErr    err;
  1398.     short    canDoAsync;
  1399.     short    metering;
  1400.     long    allocSize;
  1401.     
  1402.     // 1. Try to open the current sound input device
  1403.     err = SPBOpenDevice(nil,siWritePermission,&gsSHInVars.inRefNum);
  1404.     if (err == noErr)
  1405.         deviceOpened = true;
  1406.  
  1407.     // 2. Now let's see if this device an even handle asynchronous recording.
  1408.     if (err == noErr) {
  1409.         err = SPBGetDeviceInfo(gsSHInVars.inRefNum, siAsync, (Ptr)&canDoAsync);
  1410.         if (err == noErr && !canDoAsync)
  1411.             err = kSHErrNonAsychDevice;
  1412.     }
  1413.     
  1414.     // 3. Try to allocate memory for the guy's sound.
  1415.     if (err == noErr) {
  1416.         allocSize = (maxK * 1024) + kSHHeaderSlop;
  1417.         gsSHInVars.inHandle = NewHandle(allocSize);
  1418.         if (gsSHInVars.inHandle == nil) {
  1419.             err = MemError();
  1420.             if (err == noErr)
  1421.                 err = memFullErr;
  1422.         }
  1423.         if (err == noErr)
  1424.             allocated = true;
  1425.     }
  1426.         
  1427.     // 4. Set up various recording parameters (metering and quality)
  1428.     if (err == noErr) {
  1429.         metering = 1;
  1430.         SPBSetDeviceInfo(gsSHInVars.inRefNum, siLevelMeterOnOff, (Ptr)&metering);
  1431.         err = SPBSetDeviceInfo(gsSHInVars.inRefNum, siRecordingQuality, (Ptr)&quality);
  1432.     }
  1433.     
  1434.     // 5. Call SHGetDeviceSettings to determine a bunch of information we'll need to
  1435.     // make a header for this sound.
  1436.     if (err == noErr) {
  1437.         err = SHGetDeviceSettings(gsSHInVars.inRefNum, &gsSHInVars.numChannels,
  1438.             &gsSHInVars.sampleRate, &gsSHInVars.sampleSize, &gsSHInVars.compType);
  1439.     }
  1440.     
  1441.     // 6. Create a header for this sound.
  1442.     if (err == noErr) {
  1443.         err = SetupSndHeader(gsSHInVars.inHandle, gsSHInVars.numChannels, gsSHInVars.sampleRate, gsSHInVars.sampleSize,
  1444.             gsSHInVars.compType, kSHBaseNote, allocSize, &gsSHInVars.headerLength);
  1445.     }
  1446.     
  1447.     // 7. Lock the input sound handle and set up the input parameter block.
  1448.     if (err == noErr) {
  1449.         MoveHHi(gsSHInVars.inHandle);
  1450.         HLock(gsSHInVars.inHandle);
  1451.         
  1452.         allocSize -= gsSHInVars.headerLength;
  1453.         gsSHInVars.inPB.inRefNum = gsSHInVars.inRefNum;
  1454.         gsSHInVars.inPB.count = allocSize;
  1455.         gsSHInVars.inPB.milliseconds = 0;
  1456.         gsSHInVars.inPB.bufferLength = allocSize;
  1457.         gsSHInVars.inPB.bufferPtr = *gsSHInVars.inHandle + gsSHInVars.headerLength;
  1458.         gsSHInVars.inPB.completionRoutine = (ProcPtr)SHRecordCompletion;
  1459.         gsSHInVars.inPB.interruptRoutine = nil;
  1460.         gsSHInVars.inPB.userLong = SetCurrentA5();        // for our completion routine
  1461.         gsSHInVars.inPB.error = noErr;
  1462.         gsSHInVars.inPB.unused1 = 0;
  1463.         
  1464.         err = noErr;
  1465.     }
  1466.     
  1467.     // 8. Finally, if all went well, set our recording flag, make sure our record
  1468.     // completion flag is clear, and initiate asychronous recording.
  1469.     if (err == noErr) {
  1470.         gsSHInVars.recording = true;
  1471.         gsSHInVars.recordComplete = false;
  1472.         gsSHInVars.appComplete = doneFlag;
  1473.         gsSHInVars.paused = false;
  1474.         if (gsSHInVars.appComplete != nil)
  1475.             *gsSHInVars.appComplete = false;
  1476.         
  1477.         err = SPBRecord(&gsSHInVars.inPB, kSHAsync);
  1478.     }
  1479.     
  1480.     // Now clean up any errors that might have occurred.
  1481.     if (err != noErr) {
  1482.         gsSHInVars.recording = false;
  1483.         if (deviceOpened)
  1484.             SPBCloseDevice(gsSHInVars.inRefNum);
  1485.         if (allocated) {
  1486.             DisposeHandle(gsSHInVars.inHandle);
  1487.             gsSHInVars.inHandle = nil;
  1488.         }
  1489.     }
  1490.     
  1491.     return(err);
  1492. }
  1493.  
  1494. //=======================================================================================
  1495. //
  1496. //    pascal OSErr SHGetRecordedSound(Handle *theSound)
  1497. //
  1498. //    Summary:
  1499. //        This routine returns the sound handle from the last sound the Helper recorded.
  1500. //
  1501. //    Scope:
  1502. //        Public.
  1503. //
  1504. //    Parameters:
  1505. //        theSound        A pointer to a Handle by which to return the sound handle.
  1506. //
  1507. //    Returns:
  1508. //        kSHErrNoRecording        If there IS NO "last recorded sound"
  1509. //        OSErr                    If recording stopped because of an error
  1510. //        noErr                    Otherwise.
  1511. //
  1512. //    Operation:
  1513. //        This routine returns the sound handle (stored in the inHandle field of the
  1514. //        gsSHInVars struct) from the last sound that was recorded by the Helper.  If
  1515. //        the recording died by an error (other than abortErr), then the error is returned
  1516. //        and *theSound is set to nil.  SHGetRecordedSound is the method by which you
  1517. //        retrieve a sound handle, once you know (by whatever means) that recording is
  1518. //        complete.
  1519. //
  1520. //=======================================================================================
  1521. pascal OSErr SHGetRecordedSound(Handle *theSound)
  1522. {
  1523.     if (gsSHInVars.recordComplete) {
  1524.         if (gsSHInVars.recordErr != noErr) {
  1525.             *theSound = nil;
  1526.             return(gsSHInVars.recordErr);
  1527.         } else {
  1528.             *theSound = gsSHInVars.inHandle;
  1529.             return(noErr);
  1530.         }
  1531.     } else {
  1532.         *theSound = nil;
  1533.         return(kSHErrNoRecording);
  1534.     }
  1535. }
  1536.  
  1537. //=======================================================================================
  1538. //
  1539. //    pascal OSErr SHRecordStop(void)
  1540. //
  1541. //    Summary:
  1542. //        This routine immediately stops sound recording.
  1543. //
  1544. //    Scope:
  1545. //        Public.
  1546. //
  1547. //    Parameters:
  1548. //        None.
  1549. //
  1550. //    Returns:
  1551. //        OSErr        Whatever SPBStopRecording returns.
  1552. //
  1553. //    Operation:
  1554. //        This routine simply calls SPBStopRecording to immediately stop sound recording.
  1555. //        It sets the parameter block's error code to abortErr, and calls the callback
  1556. //        routine.  Use this routine to implement a "stop" button.
  1557. //
  1558. //=======================================================================================
  1559. pascal OSErr SHRecordStop(void)
  1560. {
  1561.     if (gsSHInVars.recording)
  1562.         return(SPBStopRecording(gsSHInVars.inRefNum));
  1563. }
  1564.  
  1565. //=======================================================================================
  1566. //
  1567. //    pascal OSErr SHRecordPause(void)
  1568. //
  1569. //    Summary:
  1570. //        This routine pauses sound recording.
  1571. //
  1572. //    Scope:
  1573. //        Public.
  1574. //
  1575. //    Parameters:
  1576. //        None.
  1577. //
  1578. //    Returns:
  1579. //        kSHErrNotRecording        If we're not recording right now.
  1580. //        kSHErrAlreadyPaused        If recording is already paused.
  1581. //        OSErr                    Whatever SPBPauseRecording returns.
  1582. //
  1583. //    Operation:
  1584. //        This routine pauses sound recording if we ARE recording and we're not already
  1585. //        paused.  Use this routine to implement a "pause" button.
  1586. //
  1587. //=======================================================================================
  1588. pascal OSErr SHRecordPause(void)
  1589. {
  1590.     OSErr    err;
  1591.     
  1592.     if (gsSHInVars.recording) {
  1593.         if (!gsSHInVars.paused) {
  1594.             err = SPBPauseRecording(gsSHInVars.inRefNum);
  1595.             gsSHInVars.paused = (err == noErr);
  1596.             return(err);
  1597.         } else return(kSHErrAlreadyPaused);
  1598.     } else return(kSHErrNotRecording);
  1599. }
  1600.  
  1601. //=======================================================================================
  1602. //
  1603. //    pascal OSErr SHRecordContinue(void)
  1604. //
  1605. //    Summary:
  1606. //        This routine resumes recording when recording has previously been paused.
  1607. //
  1608. //    Scope:
  1609. //        Public.
  1610. //
  1611. //    Parameters:
  1612. //        None.
  1613. //
  1614. //    Returns:
  1615. //        kSHErrNotRecording        If we're not recording right now.
  1616. //        kSHErrAlreadyContinued    If we're not paused.
  1617. //        OSErr                    Whatever SPBResumeRecording returns.
  1618. //
  1619. //    Operation:
  1620. //        This routine continues sound recording if we ARE recording and we've been
  1621. //        previously paused.  Use this routine to implement a "unpause" button.
  1622. //
  1623. //=======================================================================================
  1624. pascal OSErr SHRecordContinue(void)
  1625. {
  1626.     OSErr    err;
  1627.     
  1628.     if (gsSHInVars.recording) {
  1629.         if (gsSHInVars.paused) {
  1630.             err = SPBResumeRecording(gsSHInVars.inRefNum);
  1631.             gsSHInVars.paused = !(err == noErr);
  1632.             return(err);
  1633.         } else return(kSHErrAlreadyContinued);
  1634.     } else return(kSHErrNotRecording);
  1635. }
  1636.  
  1637. //=======================================================================================
  1638. //
  1639. //    pascal OSErr SHRecordStatus(SHRecordStatusRec *recordStatus)
  1640. //
  1641. //    Summary:
  1642. //        This routine returns status information on sound that is being recorded.
  1643. //
  1644. //    Scope:
  1645. //        Public.
  1646. //
  1647. //    Parameters:
  1648. //        recordStatus    A pointer to a SHRecordStatusRec into which to store the
  1649. //                        recording status.
  1650. //
  1651. //    Returns:
  1652. //        kSHErrNotRecording        If we're not recording right now.
  1653. //        OSErr                    Whatever SPBGetRecordingStatus returns.
  1654. //        noErr                    Otherwise.
  1655. //
  1656. //    Operation:
  1657. //        If we're currently recording, we call SPBGetRecordingStatus.  It tells us lots
  1658. //        of handy things, most of which we return via recordStatus, then we give a status
  1659. //        of either shrPaused or shrRecording, depending upon the state of the
  1660. //        gsSHInVars.paused flag.  If recording is complete, we return shrFinished.  If an
  1661. //        error occurs, we give a status of shrError.
  1662. //
  1663. //=======================================================================================
  1664. pascal OSErr SHRecordStatus(SHRecordStatusRec *recordStatus)
  1665. {
  1666.     short            recStatus;
  1667.     OSErr            err;
  1668.     unsigned long    totalSamplesToRecord,numberOfSamplesRecorded;
  1669.     
  1670.     if (gsSHInVars.recording) {
  1671.         err = SPBGetRecordingStatus(gsSHInVars.inRefNum, &recStatus,
  1672.             &recordStatus->meterLevel, &totalSamplesToRecord, &numberOfSamplesRecorded,
  1673.             &recordStatus->totalRecordTime, &recordStatus->currentRecordTime);
  1674.         if (err == noErr)
  1675.             recordStatus->recordStatus = (gsSHInVars.paused ? shrPaused : shrRecording);
  1676.         else recordStatus->recordStatus = shrError;
  1677.         return(err);
  1678.     } else if (gsSHInVars.recordComplete) {
  1679.         recordStatus->recordStatus = shrFinished;
  1680.         recordStatus->meterLevel = 0;
  1681.         // Don't know about the other fields -- just leave 'em
  1682.         return(noErr);
  1683.     } else return(kSHErrNotRecording);
  1684. }
  1685.